﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Web;
using System.IO;

namespace AliCMS.VoteModule.Bll
{
    public partial class Vote : DbObjectBase, IVote
    {
        public class Result : DbObjectBase, VoteModule.Vote.IResult
        {
            public Result(int instanceID, string lang, bool checkRight, string database)
                : base(instanceID, lang, checkRight, database)
            {
            }

            public override object ExecuteService(HttpContext context)
            {
                object result = null;

                string operation = context.Request.QueryString["Operation"];
                if (operation == "Add")
                {
                    Dictionary<string, object> item = new Dictionary<string, object>();
                    item[Alias.Vote.Result.VoteID] = context.Request.Form["VoteID"];
                    item[Alias.Vote.Result.OptionID] = context.Request.Form["OptionID"];

                    result = Add(item);
                }
                else if (operation == "Delete")
                {
                    string id = context.Request.QueryString["ID"];

                    string[] ids = id.Split('|');
                    for (int i = 0; i < ids.Length; i++)
                    {
                        if (String.IsNullOrEmpty(ids[i]))
                            continue;

                        Delete(Convert.ToInt32(ids[i]));
                    }
                }
                else if (operation == "List")
                {
                    string value = null;

                    int page = -1;
                    value = context.Request.QueryString["Page"];
                    if (value != null) page = Convert.ToInt32(value);

                    int pageSize = -1;
                    value = context.Request.QueryString["PageSize"];
                    if (value != null) pageSize = Convert.ToInt32(value);

                    string condition = context.Request.QueryString["Condition"];
                    string sort = context.Request.QueryString["Sort"];

                    result = List(page, pageSize, condition, sort);
                }
                else if (operation == "GetInnerIDFromGuid")
                {
                    Guid guid = new Guid(context.Request.QueryString["ID"]);
                    result = GetInnerIDFromGuid(guid);
                }
                else
                {
                    throw new Exception("lang_header_param");
                }

                return result;
            }

            public int GetInnerIDFromGuid(Guid guid)
            {
                return Dal.GetInnerIDFromGuid(guid);
            }
            public Guid GetGuidFromInnerID(object id)
            {
                return Dal.GetGuidFromInnerID(id);
            }
            public Dictionary<string, object> Get(object id)
            {
                if (CheckRight)
                {
                    Guid guid;
                    if (id is Guid)
                        guid = (Guid)id;
                    else
                        guid = Dal.GetGuidFromInnerID(id);
                    ValidateRight("Get", guid);
                }

                return Dal.Get(id);
            }
            public Guid Add(Dictionary<string, object> item)
            {
                if (CheckRight)
                {
                    ValidateRight("Add", Guid.Empty);
                }

                if (!item.ContainsKey(Alias.Vote.Result.ID) || item[Alias.Vote.Result.ID].ToString() == String.Empty)
                    item[Alias.Vote.Result.ID] = Guid.NewGuid();
                else if (!(item[Alias.Vote.Result.ID] is Guid))
                    item[Alias.Vote.Result.ID] = new Guid(item[Alias.Vote.Result.ID].ToString());

                if (!(item[Alias.Vote.Result.VoteID] is Guid))
                    item[Alias.Vote.Result.VoteID] = new Guid(item[Alias.Vote.Result.VoteID].ToString());

                if (!(item[Alias.Vote.Result.OptionID] is Guid))
                    item[Alias.Vote.Result.OptionID] = new Guid(item[Alias.Vote.Result.OptionID].ToString());

                item[Alias.Vote.Result.IP] = HttpContext.Current.Request.UserHostAddress;

                #region 检查是否可以添加
                Dictionary<string, object> vote;
                using (IVote bll = (IVote)Manager.CreateObject("Vote", InstanceID, Lang, false))
                {
                    vote = bll.Get(item[Alias.Vote.Result.VoteID]);
                }

                if (!Convert.IsDBNull(vote[Alias.Vote.TimeLimitForSameUser]))
                {
                    int timeLimit = Convert.ToInt32(vote[Alias.Vote.TimeLimitForSameUser]);

                    #region 如果cookie存在，表示已投过票
                    HttpCookie cookie = HttpContext.Current.Request.Cookies[item[Alias.Vote.Result.VoteID].ToString()];
                    if (cookie != null)
                    {
                        Exception exp = new Exception("lang_exceed_time_limit_for_same_user");
                        exp.Data.Add("InstanceID", InstanceID);
                        throw exp;
                    }
                    #endregion

                    #region 检查当前ip是否投过票
                    string ip = HttpContext.Current.Request.UserHostAddress;
                    DataTable table = Dal.List(1, 1, Alias.Vote.Result.VoteID + "=" + vote[Alias.Vote.ID] + " and " + Alias.Vote.Result.IP + "='" + ip + "'", null);
                    if (table.Rows.Count > 0 && Convert.ToDateTime(table.Rows[0][Alias.Vote.Result.CreateTime]).AddMinutes(timeLimit) < DateTime.Now)
                    {
                        Exception exp = new Exception("lang_exceed_time_limit_for_same_user");
                        exp.Data.Add("InstanceID", InstanceID);
                        throw exp;
                    }
                    #endregion

                    #region 写入Cookie
                    cookie = new HttpCookie(item[Alias.Vote.Result.VoteID].ToString());
                    cookie.Expires = DateTime.Now.Add(new TimeSpan(0, 0, timeLimit, 0));
                    cookie.Domain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];
                    cookie.Path = "/";
                    HttpContext.Current.Response.SetCookie(cookie);
                    #endregion
                }
                #endregion

                Dictionary<string, string> user = Manager.User;
                if (user != null)
                {
                    item[Alias.Vote.Result.Creator] = user["Name"];
                    item[Alias.Vote.Result.CreatorID] = new Guid(user["ID"]);
                }

                if (item.ContainsKey(Alias.Vote.Result.CreateTime))
                    item[Alias.Vote.Result.CreateTime] = Convert.ToDateTime(item[Alias.Vote.Result.CreateTime]);
                else
                    item[Alias.Vote.Result.CreateTime] = DateTime.Now;

                Dal.Add(item);

                return (Guid)item[Alias.Vote.Result.ID];
            }
            public void Modify(int id, Dictionary<string, object> changes)
            {
                throw new NotImplementedException();
            }
            public void Delete(int id)
            {
                if (CheckRight)
                {
                    Guid guid = Dal.GetGuidFromInnerID(id);
                    ValidateRight("Delete", guid);
                }

                Dal.Delete(id);
            }
            public DataTable List(int page, int pageSize, string condition, string sort)
            {
                if (CheckRight)
                {
                    ValidateRight("List", Guid.Empty);
                }

                return Dal.List(page, pageSize, condition, sort);
            }
            public int GetRecordCount(string condition)
            {
                return Dal.GetRecordCount(condition);
            }

            #region Properties
            private Dal.Vote.IResult Dal
            {
                get { return (Dal.Vote.IResult)DalBase; }
            }
            #endregion
        }
    }
}
